#!/bin/bash
cd ~/app-root/data/temp/sign/
useragent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0"
getsid(){
    i=$1
    curl "$(grep '^loginUrl' $i|awk -F ': ' '{print $2}')" --user-agent "$useragent" --Cookie "$(grep '^Cookie' $i|awk -F ': ' '{print $2}')" --data "$(grep '^loginData' $i|awk -F ': ' '{print $2}')" -D log.txt >/dev/null 2>&1

    if grep -q 'ONEPLUSID' log.txt; then
        sed -i "/Cookie:\ /s#ONEPLUSID.*#$(grep -o 'ONEPLUSID=[a-zA-Z0-9_%]*' log.txt)#" $i
    elif grep -q 'gfan\.com' log.txt; then
        sed -i "/Cookie:\ /c Cookie:\ $(grep -o '[a-zA-Z0-9_%]\{1,\}_saltkey=[a-zA-Z0-9_%]*' log.txt); $(grep -o '[a-zA-Z0-9_]\{1,\}_auth=[a-zA-Z0-9_%]*' log.txt)" $i
    fi
}

sign(){
    i=$1
    n=$2
    curl "$(grep "^signUrl${n}" $i|awk -F ': ' '{print $2}')" --user-agent "$useragent" --Cookie "$(grep '^Cookie' $i|awk -F ': ' '{print $2}')" --data "$(grep "^signData${n}" $i|awk -F ': ' '{print $2}')" > result.txt
}

List=$(ls *)
if [ "$List" ]; then
    for i in $List; do
        sed -i 's#\"##g' $i
        s=$(grep -o '^title[0-9]' $i|grep -o '[0-9]' |tail -1)
        for ((n=1;n<=$s;n++)); do
            if ! grep -q "$(grep "^title${n}" $i|awk -F ': ' '{print $2}')：" ~/app-root/repo/log/sign.log; then
                echo "$(grep "^title${n}" $i|awk -F ': ' '{print $2}')：从未签到" >> ~/app-root/repo/log/sign.log
            elif grep -q "$(grep "^title${n}" $i|awk -F ': ' '{print $2}')：$(date -d "8 hour" -u "+%Y年%m月%d日")" ~/app-root/repo/log/sign.log; then
                continue
            fi
            sign "$i" "$n"
            if grep -E -q '成功|已经|signed|succe|already' result.txt; then
                sed -i "/$(grep "^title${n}" $i|awk -F ': ' '{print $2}')：/s#：.*#：$(date -d "8 hour" -u "+%Y年%m月%d日 %H:%M")#" ~/app-root/repo/log/sign.log
            else
                getsid "$i"
                sign "$i" "$n"
                if grep -E -q '成功|已经|signed|succe|already' result.txt; then
                    sed -i "/$(grep "^title${n}" $i|awk -F ': ' '{print $2}')：/s#：.*#：$(date -d "8 hour" -u "+%Y年%m月%d日 %H:%M")#" ~/app-root/repo/log/sign.log
                fi
            fi
        done
    done
fi
rm -f log.txt result.txt